<template>
	<div class="base">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px">

			<el-form-item label="类别" prop="declarationType">
				<el-select v-model="dataForm.declarationType" placeholder="请选择" @change="declarationTypeSelect">
					<el-option v-for="item in declarationTypeOptions" :key="item.value" :label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="单位编号" prop="unitNumber">
				<el-input v-model="dataForm.unitNumber" placeholder="单位编号" />
			</el-form-item>
			<el-form-item label="单位名称" prop="unitName">
				<el-input v-model="dataForm.unitName" placeholder="单位名称" />
			</el-form-item>
			<el-form-item label="单位地址" prop="unitAddress">
				<el-input v-model="dataForm.unitAddress" placeholder="单位地址" />
			</el-form-item>
			<el-form-item label="所属区镇" prop="area">
				<el-select v-model="dataForm.area" placeholder="请选择">
					<el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="申报人" prop="applicant">
				<el-input v-model="dataForm.applicant" placeholder="申报人" />
			</el-form-item>
			<el-form-item label="申报人手机" prop="applicantPhone">
				<el-input v-model="dataForm.applicantPhone" placeholder="申报人手机" />
			</el-form-item>

			<el-form-item :label="dataForm.declarationType==0?'退工花名册':'参保花名册'" prop="attachment1">
				<div class="attachment-content">
					<el-upload v-model="dataForm.attachment1" class="upload-de" ref="attachment1" action=""
						:on-change="handleChange1" :on-preview="handlePreview1" :on-remove="handleRemove1"
						:multiple="false" :limit="1" :auto-upload="false">
						<div class="upload-part1">
							<el-button slot="trigger" type="primary">选取文件</el-button>
						</div>

					</el-upload>
					<el-button type="success" style="margin-left: 20px;" @click="downloadDeFileExcel">下载模板</el-button>

				</div>
			</el-form-item>
			<el-form-item label="承诺书" prop="attachment2">
				<div class="attachment-content">
					<el-upload v-model="dataForm.attachment2" class="upload-pr" ref="attachment2" action=""
						:on-change="handleChange2" :on-preview="handlePreview2" :on-remove="handleRemove2"
						:multiple="false" :limit="1" :auto-upload="false">
						<div class="upload-part1">
							<el-button slot="trigger" type="primary">选取文件</el-button>
						</div>
					</el-upload>
					<el-button type="success" style="margin-left: 20px;" @click="downloadPrFileExcel">下载模板</el-button>
					<div style="margin-left: 20px; color: red;">注：转换成PDF或图片格式上传，并确保公章清晰，如公章缺失或与附件一中的单位名称不一致，视作本次备案登记无效。
					</div>

				</div>
			</el-form-item>

		</el-form>
		<span slot="footer" class="footer">
			<el-button class="btn-submit" type="success" @click="submitClick()">提交</el-button>
		</span>
	</div>
</template>

<style lang="css" scoped>
</style>

<script>
	import {
		outEndTime
	} from '@/common/env.js';
	import XLSX from 'xlsx';
	import axios from 'axios';
	import qs from 'qs';
	import store from '@/store'
	import {
		randomNum
	} from '@/assets/js/common.js'

	import {
		declarationSave,
	} from '@/api/enterprise/declaration'
	import Utils from '@/api/sys/menus/index'
	export default {
		components: {

		},
		data() {
			var validateUnitNumber = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('编号不能为空'));
				}
				if (value.length != 8) {
					callback(new Error('必须为8位'));
				} else {
					callback();
				}
			};
			var validatePhone = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('手机号不能为空'));
				} else {
					const reg = /^1[0-9][0-9]\d{8}$/
					console.log(reg.test(value));
					if (reg.test(value)) {
						callback();
					} else {
						return callback(new Error('请输入正确的手机号'));
					}
				}
			};
			return {
				dataForm: {
					declarationType: 1,
				},
				dataRule: {
					declarationType: [{
						required: true,
						trigger: 'blur'
					}],
					unitNumber: [{
						required: true,
						validator: validateUnitNumber,
						trigger: 'blur'
					}],
					unitName: [{
						required: true,
						message: '单位名称不能为空',
						trigger: 'blur'
					}],
					unitAddress: [{
						required: true,
						message: '单位地址不能为空',
						trigger: 'blur'
					}],
					area: [{
						required: true,
						message: '所属区镇不能为空',
						trigger: 'blur'
					}],
					applicant: [{
						required: true,
						message: '申报人不能为空',
						trigger: 'blur'
					}],
					applicantPhone: [{
						required: true,
						validator: validatePhone,
						trigger: 'blur'
					}],
					attachment1: [{
						required: true,
						message: '参保花名册不能为空',
						trigger: 'blur'
					}],
					attachment2: [{
						required: true,
						message: '承诺书不能为空',
						trigger: 'blur'
					}],
				},
				declarationTypeOptions: [{
						value: 1,
						label: '录用'
					},
					{
						value: 0,
						label: '退工'
					}
				],
				declarationTypeValue: 0,
				areaOptions: [{
						value: '玉山镇',
						label: '玉山镇'
					},
					{
						value: '开发区',
						label: '开发区'
					},
					{
						value: '巴城',
						label: '巴城'
					},
					{
						value: '周市',
						label: '周市'
					},
					{
						value: '陆家',
						label: '陆家'
					},
					{
						value: '花桥',
						label: '花桥'
					},
					{
						value: '千灯',
						label: '千灯'
					},
					{
						value: '张浦',
						label: '张浦'
					},
					{
						value: '淀山湖',
						label: '淀山湖'
					},
					{
						value: '锦溪',
						label: '锦溪'
					},
					{
						value: '周庄',
						label: '周庄'
					}
				],
			}
		},
		created() {
			console.log('created')
			console.log(this.$store.getters.userInfo.permissions)
			if(this.$store.getters.userInfo.permissions=='1'&&
					this.$ls.get('isFirstLogin')){
				setTimeout(() => {
					this.$ls.set('isFirstLogin',false)
					Utils.$emit('notice', 'flow') //通知跳转
				}, 200)
			}
			//规定时间后，关闭退工
			const format = 'YYYY/MM/DD HH:mm:ss'
			const end = this.$moment(outEndTime, format);
			// console.log(outEndTime)
			// console.log(this.$moment(end).diff(this.$moment(), 'seconds'))
			if (this.$moment(end).diff(this.$moment(), 'seconds') < 0) {
			this.declarationTypeOptions=[{
						value: 1,
						label: '录用'
					}
				]
			}
		},
		mounted() {

		},
		destroyed() {

		},
		methods: {
			// submitUpload() {
			// 	this.$refs.upload.submit();
			// },
			handleChange1(file, fileList) {
				let isJPG = false
				if (file.raw.type == 'application/vnd.ms-excel' ||
					file.raw.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
					isJPG = true
				}
				// const isJPG = file.raw.type === 'application/vnd.ms-excel' ||
				// 	'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
				// 	console.log(isJPG)
				const isLt2M = file.raw.size / 1024 / 1024 < 50;

				if (!isJPG) {
					this.$message.error('上传文件只能是 xls或xlsx 格式!');
					this.$refs['attachment1'].clearFiles();
					return
				}
				if (!isLt2M) {
					this.$message.error('上传文件大小不能超过 50MB!');
					this.$refs['attachment1'].clearFiles();
					return
				}
				console.log(file, fileList);
				this.dataForm.attachment1 = file;
			},
			handleRemove1(file, fileList) {
				console.log(file, fileList);
			},
			handlePreview1(file) {
				console.log(file);
			},
			handleChange2(file, fileList) {
				let isJPG = false
				if (file.raw.type == 'image/jpeg' || file.raw.type == 'image/gif' ||
					file.raw.type == 'image/png' || file.raw.type == 'application/pdf') {
					isJPG = true
				}
				// const isJPG = file.raw.type === 'application/vnd.ms-excel' ||
				// 	'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
				// 	console.log(isJPG)
				const isLt2M = file.raw.size / 1024 / 1024 < 50;

				if (!isJPG) {
					this.$message.error('上传文件只能是图片或PDF格式!');
					this.$refs['attachment2'].clearFiles();
					return
				}
				if (!isLt2M) {
					this.$message.error('上传文件大小不能超过 50MB!');
					this.$refs['attachment2'].clearFiles();
					return
				}
				this.dataForm.attachment2 = file;
			},
			handleRemove2(file, fileList) {
				console.log(file, fileList);
			},
			handlePreview2(file) {
				console.log(file);
			},
			declarationTypeSelect(val) {
				console.log(val)
				this.dataForm.declarationType = val
			},
			// 读取文件
			file2Xce(file) {
				return new Promise(function(resolve, reject) {
					const reader = new FileReader();
					reader.onload = function(e) {
						const data = e.target.result;
						this.wb = Xlsx.read(data, {
							type: "binary"
						});
						const result = [];
						this.wb.SheetNames.forEach(sheetName => {

							result.push({
								sheetName: sheetName,
								sheet: Xlsx.utils.sheet_to_json(this.wb.Sheets[sheetName])
							})
						})
						resolve(result);
					}
					reader.readAsBinaryString(file.raw);
				})
			},
			downloadDeFileExcel() {
				// let a = document.createElement("a");
				if (this.dataForm.declarationType == 0) {
					//退工
					// a.href = "http://image.szhtj.cn/用人单位退工停保登记花名册.xlsx";
					// a.setAttribute("download", "用人单位退工停保登记花名册模板");
					this.download("http://image.szhtj.cn/用人单位退工停保登记花名册.xlsx", "用人单位退工停保登记花名册模板");
					
				} else {
					// a.href = "http://image.szhtj.cn/江苏省用人单位用工参保登记花名册.xlsx";
					// a.setAttribute("download", "江苏省用人单位用工参保登记花名册模板");
					this.download("http://image.szhtj.cn/江苏省用人单位用工参保登记花名册.xlsx", "用人单位用工参保登记花名册模板");
					
				}
				// a.click();
				
			},
			downloadPrFileExcel() {
				// let a = document.createElement("a");
				// a.href = "http://image.szhtj.cn/临时备案系统情况说明.docx";
				// a.setAttribute("download", "临时备案系统情况说明模板");
				// a.click();
				this.download("http://image.szhtj.cn/临时备案系统情况说明.docx", "临时备案系统情况说明模板");
			},
			submitClick() {

				console.log(this.dataForm);
				this.$refs['dataForm'].validate(valid => {
					if (valid) {
						const loading = this.$loading({
							lock: true,
							text: '加载中',
							spinner: 'el-icon-loading',
							background: 'rgba(0, 0, 0, 0.7)'
						})
						let params = new FormData() // 创建form对象
						params.append('deFile', this.dataForm.attachment1.raw) // 通过append向form对象添加数据
						params.append('prFile', this.dataForm.attachment2.raw)
						params.append('unitNumber', this.dataForm.unitNumber) // 添加form表单中其他数据
						params.append('unitName', this.dataForm.unitName)
						params.append('unitAddress', this.dataForm.unitAddress)
						params.append('declarationType', this.dataForm.declarationType)
						params.append('area', this.dataForm.area)
						params.append('applicant', this.dataForm.applicant)
						params.append('applicantPhone', this.dataForm.applicantPhone)

						this.request(declarationSave, params, this, data => {
							console.log(data);
							loading.close();
							this.$ls.set("unitNumber", this.dataForm.unitNumber);
							//清除数据
							this.dataForm = {
								declarationType: 1,
							}
							this.$refs.attachment1.clearFiles();
							this.$refs.attachment2.clearFiles();
							Utils.$emit('notice', 'staff') //通知跳转
							return
						}, true, fail => {
							console.log(fail);
							loading.close();
							this.error(fail.message ? fail.message : '服务异常', () => {
								// window.location.reload()
								//不清除数据
								// this.dataForm = {
								// 	declarationType: 1,
								// }
								// this.$refs.attachment1.clearFiles();
								// this.$refs.attachment2.clearFiles();
							});
						}, error => {
							console.log(error);
						})
					} else {
						console.log("error submit!!");
						return true;
					}
				});


				// let userInfo = this.$ls.get("userInfo");
				// let headers = {
				//     'Content-Type':'multipart/form-data',
				// 	'Authorization':userInfo.token
				//   }
				// axios.post('http://localhost:8182/declaration/save', params, {headers: headers})
			},



		}
	}
</script>
<style lang="less" scoped>
	.base {
		margin-right: 100px;
	}

	.upload-de,
	.upload-pr {
		display: flex;
		flex-direction: row-reverse;
		justify-content: flex-end;
	}

	.upload-part1 {
		display: flex;
	}

	.el-upload-list__item-name {
		text-decoration: underline;
	}

	.el-upload-list {
		margin-right: 20px;
	}

	.attachment-content {
		display: flex;
	}

	.footer {
		display: flex;
		justify-content: flex-end;
	}

	.btn-submit {
		width: 200px;
	}
</style>
